package com.sy.msgview.component

import android.content.res.Configuration
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import coil.compose.AsyncImage
import com.sy.msgview.QQMsgItem
import com.sy.msgview.QQViewModel
import com.sy.msgview.ui.theme.Pink40
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.util.Locale

@Composable
fun MsgView(model: QQViewModel, qq: Long, navController: NavController) {
	Surface(contentColor = MaterialTheme.colorScheme.onSurface) {
		Column {
			Row(
				modifier = Modifier
					.fillMaxWidth()
					.heightIn(55.dp)
					.background(MaterialTheme.colorScheme.surface),
				verticalAlignment = Alignment.CenterVertically
			) {
				IconButton(onClick = { navController.popBackStack() }) {
					Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back Arrow")
				}
				Spacer(modifier = Modifier.width(5.dp))
				Text(text = qq.toString(), fontWeight = FontWeight.Bold)
			}
			var showDate by remember {
				mutableLongStateOf(-1L)
			}
			val pattern = DateTimeFormatter.ofPattern("yyyy/MM/dd EEEE_HH:mm:ss", Locale.CHINA)
			val lazyListState = rememberLazyListState()
			val loadMore by remember {
				derivedStateOf {
					val offset = 2
					val layoutInfo = lazyListState.layoutInfo
					val totalItemsCount = layoutInfo.totalItemsCount
					val lastVisibleItemIndex = (layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0) + 1
					val b = (lastVisibleItemIndex > (totalItemsCount - offset)) && totalItemsCount > offset
//					Utils.showLog("currentIndex:${lastVisibleItemIndex},totalCount:${totalItemsCount}, result:${b}")
					b
				}
			}

			val msgList = model.msgList.collectAsState(initial = listOf()).value
			LaunchedEffect(null) { model.getQQMsg(qq, next = false) }
			LaunchedEffect(loadMore) {
				snapshotFlow { loadMore }
					.distinctUntilChanged()
					.filter { it }
					.collect {
						model.getQQMsg(qq)
					}
			}
			LazyColumn(
				modifier = Modifier.fillMaxHeight(),
				contentPadding = PaddingValues(start = 5.dp, end = 5.dp, bottom = 20.dp),
				reverseLayout = true,
				verticalArrangement = Arrangement.Top,
				state = lazyListState
			) {
				items(msgList) {
					val time =
						LocalDateTime.ofEpochSecond(it.time ?: 0, 0, ZoneOffset.ofHours(8)).format(pattern)
					var show = false
					if ((showDate == -1L || it.date != showDate) && it.date != null) {
						showDate = it.date
						show = true
					}
					Row(Modifier.fillMaxWidth(), Arrangement.Center) {
						Text(
							text = if (show) time.split("_")[0] else "",
							fontSize = 10.sp,
							color = Color.Gray
						)
					}
					MsgItemView(it, time)
				}
			}
		}
	}
}


@Composable
fun MsgItemView(msgItem: QQMsgItem, time: String) {
	val direction = if (msgItem.is_me != 0) Arrangement.End else Arrangement.Start
	Row(
		modifier = Modifier
			.fillMaxWidth()
			.padding(10.dp, 10.dp),
		horizontalArrangement = direction
	) {
		Row(
			modifier = Modifier.fillMaxWidth(0.75f),
			horizontalArrangement = direction
		) {
			if (msgItem.is_me == 0) {
				AsyncImage(
					model = "https://q1.qlogo.cn/g?b=qq&nk=${msgItem.send_qq}}&s=100",
					contentDescription = "avatar",
					modifier = Modifier.clip(RoundedCornerShape(5.dp))
				)
				Spacer(modifier = Modifier.width(5.dp))
			}
			Column(horizontalAlignment = if (msgItem.is_me != 0) Alignment.End else Alignment.Start) {
				Text(
					text = "${msgItem.send_name} ${time.split("_")[1]}",
					fontSize = 10.sp,
					color = Color.Gray
				)
				Surface(
					shape = RoundedCornerShape(5.dp), color = Pink40
				) {
					Text(modifier = Modifier.padding(5.dp), text = msgItem.msg ?: "", color = Color.White)
				}
			}
			if (msgItem.is_me != 0) {
				Spacer(modifier = Modifier.width(5.dp))
				AsyncImage(
					model = "https://q1.qlogo.cn/g?b=qq&nk=${msgItem.send_qq}}&s=100",
					contentDescription = "avatar",
					modifier = Modifier.clip(RoundedCornerShape(5.dp))
				)
			}
		}
	}
}

@Preview(
	showSystemUi = true, showBackground = true,
	uiMode = Configuration.UI_MODE_NIGHT_NO or Configuration.UI_MODE_TYPE_NORMAL, apiLevel = 33
)
@Composable
fun Tmp() {
	MsgItemView(QQMsgItem(123, 887070782, 1162617171, "hhh", "zzzzzzzzzz", 13, 23, 1), "sd_12")
}
